package com.imooc.product.design.sing;

import java.io.*;

/**
 * Created on 2020/2/3.
 *
 * @author Grak
 * @since 1.0
 */
public class HungraySingleton implements Serializable{
    private final static HungraySingleton hungraySingleton = new HungraySingleton();

    private HungraySingleton(){
        if(hungraySingleton != null){
            throw new RuntimeException("单例不允许反射构建！！");
        }
    }

    public static HungraySingleton getInstance(){
        return hungraySingleton;
    }

    private Object readResolve(){
        return hungraySingleton;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        HungraySingleton singleton = HungraySingleton.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("single_file"));
        oos.writeObject(singleton);

        File file = new File("single_file");
        ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));
        HungraySingleton otherSingleton = (HungraySingleton)oin.readObject();

        System.out.println(singleton);
        System.out.println(otherSingleton);
        System.out.println(singleton == otherSingleton);
    }
}
